/**
 * Created by syf on 2015/11/14.
 */

var sellerM = require("../models/login.js");

module.exports = {
    gotoLoginPage: function (req, res, next) {
        if(req.session.userID) {
            res.redirect("order");
        }else   {
           res.render("login", {mess: ""});
        }
    },

    getSellerBySellerName: function (req, res, next) {
        if(!req.session.userID) {
            var sellerLoginName = req.param("txtLoginName");
            var password = req.param("txtPassword");
            if (sellerLoginName != "" && password != "") {
                password = md5(password);
                sellerM.getSellerBySellerName(sellerLoginName).then(function (seller) {
                    if (seller.length > 0) {
                        if (seller[0]._serverData["status"] == 1) {
                            if (seller[0]._serverData["password"] == password) {
                                req.session.userID=seller[0].id;
                                req.session.areaID=seller[0]["_serverData"].areaid;

                                req.session.nickname=seller[0]["_serverData"].nickname;
                                req.session.radix=seller[0]["_serverData"].radix;
                                req.session.rebate=seller[0]["_serverData"].rebate;
                                res.redirect("myindex");
                            } else {
                                res.render("login", {mess: "-4"});
                            }
                        } else {
                            res.render("login", {mess: "-3"});
                        }
                    } else {
                        res.render("login", {mess: "-2"});
                    }
                })
            } else {
                res.render("login", {mess: "-1"});
            }
        }else{
            res.redirect("order");
        }
    }
}

function md5(data) {
    var Buffer = require("buffer").Buffer;
    var buf = new Buffer(data);
    var str = buf.toString("binary");
    var crypto = require("crypto");
    return crypto.createHash("md5").update(str).digest("hex");
}

function User(username) {
    this.name = username;
};


